package com.lgl.allpeoplevent.ventIndex.controller;

import com.lgl.allpeoplevent.base.controller.BaseController;
import com.lgl.allpeoplevent.system.service.UserCountService;
import com.lgl.allpeoplevent.util.ControllerUtil;
import com.lgl.allpeoplevent.ventIndex.service.VentUserService;
import com.lgl.scsapi.system.model.PageData;
import com.lgl.scsapi.util.utils.*;
import com.lgl.scsapi.vent.model.VentUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value="/ventUserIndex")
public class VentUserController extends BaseController {
    @Autowired
	private VentUserService ventUserService;
    @Autowired
    private UserCountService userCountService;
    @Autowired
    private RedisTemplate redisTemplate;
	@Autowired
    private StringRedisTemplate stringRedisTemplate;
	@Value("${wx.upload.path}")
	private String uploadPath;

	//发送用户注册验证码
	@RequestMapping(value="/sendRegisterCheckCode")
	public Object sendRegisterCheckCode(HttpServletRequest request){
		PageData pd = this.getPageData();
		try {
			String phone = pd.getString("phone");
			if (!Tools.checkMobileNumber(phone)) {
				pd.put("status", "6"); //号码格式不对
				return pd;
			}
			boolean isRegister = ventUserService.existsVentPhone(phone);
			if(isRegister){
				pd.put("status", "2");//号码已注册
				return pd;
			}
			return AppUtil.checkAndSendCode(request,phone,pd,stringRedisTemplate);
		} catch (Exception e) {
            log.error(e.toString(),e);
			pd.put("status", "3");//获取验证码失败
		}
		return pd;
	}
	//已经登录的后台发送注册验证码
	@RequestMapping(value="/sendCodeByLogin")
	public Object sendCodeByLogin(HttpServletRequest request){
		PageData pd = new PageData(3);
		try {
			VentUser ventUser = this.getSessionUser();
			if (ventUser == null){
				pd.put("status", "3");//未登录
				return pd;
			}
			return AppUtil.checkAndSendCode(request,ventUser.getPhone(),pd,stringRedisTemplate);
		} catch (Exception e) {
			log.error(e.toString(),e);
			pd.put("status", "0");//获取验证码失败
		}
		return pd;
	}
	//PC端前台未登录时修改密码时发送验证码，短信登录时的验证码
	@RequestMapping(value="/sendCodeByNoLogin")
	public Object sendCodeByNoLogin(HttpServletRequest request){
		PageData pd = new PageData(3);
		try {
			String phone = request.getParameter("phone");
			//号码格式不对
			if (!Tools.checkMobileNumber(phone)) {
				pd.put("status", "6");
				return pd;
			}
			//手机号码未注册
			if (!ventUserService.existsVentPhone(phone)){
				pd.clear();
				pd.put("status", "3");
				return pd;
			}
			return AppUtil.checkAndSendCode(request,phone,pd,stringRedisTemplate);
		} catch (Exception e) {
			log.error(e.toString(),e);
			pd.put("status", "0");//获取验证码失败
		}
		return pd;
	}
	//判断手机号是否已存在,true:存在，false:不存在
	@RequestMapping(value="/isExistsPhone")
	public boolean isExistsPhone(HttpServletRequest request){
		String phone = request.getParameter("phone");
		return ventUserService.existsVentPhone(phone);
	}
	//密码登录
	@RequestMapping(value="/toLoginByPwd", produces="application/json;charset=UTF-8")
	public Object toLoginByPwd() {
		PageData pd = this.getPageData();
		//如果isMobile=Y，表示从微信端传来的登录请求，则不验证滑块信息
		String dragMoveX = (String) pd.remove("dragMoveX"), isMobile = (String) pd.remove("isMobile");
		dragMoveX = dragMoveX == null ? "0" : dragMoveX;
    	Integer moveX = (Integer) getRequest().getSession().getAttribute("location_x");
    	//如果滑块移动不在4像素范围内，则说明验证失败
    	if (!"Y".equals(isMobile)) {
    		if (moveX == null || moveX < 1){
                pd.clear();
                pd.put("status", "6");
				return pd;
			}
    		if ((Integer.valueOf(dragMoveX) > moveX + 4) || (Integer.valueOf(dragMoveX) <= moveX - 4)) {
                pd.clear();
    		    pd.put("status", "2");
            	return pd;
            }
		}
		return ventUserService.toLogin(pd);
	}
	//验证码登录
	@RequestMapping(value="/toLoginByCode")
	public Object toLoginByCode(HttpServletRequest request) {
		PageData loginMap = new PageData(10);
		String userPhone = request.getParameter("userPhone"),
				checkCode = request.getParameter("code");
		if (StringUtils.isEmpty(userPhone) || StringUtils.isEmpty(checkCode)){
			loginMap.put("status","1");
			return loginMap;
		}
		String redisCode = stringRedisTemplate.opsForValue().get(Constants.PHONE_CHECK_CODE_K_PRE + userPhone);
		//验证码已过期
		if (StringUtils.isEmpty(redisCode)){
			loginMap.put("status","2");
			return loginMap;
		}
		if (!checkCode.equals(redisCode)){
			loginMap.put("status","3");
			return loginMap;
		}
		VentUser codeUser = ventUserService.findByPhone(userPhone);
		if (codeUser == null){
			loginMap.put("status","5");
			return loginMap;
		}
		//用户冻结
		if ("1".equals(codeUser.getStatus())){
			loginMap.put("status","6");
			return loginMap;
		}
		return ventUserService.execLoginReturnResult(loginMap,codeUser);
	}
	//注册
	@RequestMapping("/registerVent")
	public int registerVent(HttpServletRequest request) {
		PageData pd = new PageData(3);
		try {
			String sendMsg = request.getParameter("sendMsg"),
                    phone = request.getParameter("phone"),
                    password = request.getParameter("password");
			String phoneKey = Constants.PHONE_CHECK_CODE_K_PRE + phone;
			//从redis中取验证码，并与传过来的比较
            String redisCheckCode = stringRedisTemplate.opsForValue().get(phoneKey);
			if (!StringUtils.hasText(sendMsg) || !sendMsg.equals(redisCheckCode)) {
				return 3;
			}
			//如果手机号为空
            if(StringUtils.isEmpty(phone)){
                return 4;
            }
            //如果密码为空或小于6位数
            if(StringUtils.isEmpty(password) || password.trim().length() < 6){
                return 5;
            }
			//用完了立刻删除，不要等自动过期，防止redis缓存被无用的数据占用
			stringRedisTemplate.delete(phoneKey);
			//如果存在手机号，说明手机号已被注册
			if(ventUserService.existsVentPhone(phone)) {
				return 2;
			}

            password = new SimpleHash(Constants.ALGORITHM_NAME,password,Constants.SHIRO_SALT,Constants.HASH_ITERATIONS).toHex();
            String userId = BillNumberTool.getRegisterUserId(stringRedisTemplate,1);
            pd.put("password", password);
            pd.put("userName", phone);
            pd.put("phone", phone);
            pd.put("userId", userId);
            int r = ventUserService.saveVentUser(pd);
            pd.clear();
            if (r < 1){
            	throw new Exception("注册失败，吐槽用户插入行数：" + r);
			}
            return 1;
		} catch (Exception e) {
            log.error(e.toString(),e);
		}
		return 0;
	}
	//退出
	@RequestMapping(value="/toLogout")
	public Object toLogout(){
		//shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		session.removeAttribute(Constants.SESSION_USER);
		//shiro销毁登录
		currentUser.logout();
		return "0";
	}

	//编辑个人基本信息
	@RequestMapping("/editUserInfo")
	public Object editUserInfo() {
		PageData pd = this.getPageData();
		VentUser ventUser = this.getSessionUser();
		if (ventUser == null){
			pd.clear();
			pd.put("status", "-1");
			return pd;
		}
		try {
			pd.put("userId", ventUser.getUserId());
			int row = ventUserService.editVentUser(pd);
			pd.clear();
			pd.put("status", row > 0 ? "0" : "2");
		} catch (Exception e) {
            log.error("保存用户信息出错:" + e.toString(),e);
			pd.put("status", "1");
		}
		return pd;
	}
	//修改手机号码
	@RequestMapping("/modifyMyPhone")
	public Object modifyMyPhone(HttpServletRequest request) {
		try {
			VentUser ventUser = this.getSessionUser();
			String userNewPhone = request.getParameter("newPhone"),
					checkCode = request.getParameter("checkCode");
			String modifyStatus = ventUserService.modifyMyPhone(ventUser,userNewPhone,checkCode);
			if ("0".equals(modifyStatus)) {
                redisTemplate.delete(Constants.PHONE_CHECK_CODE_K_PRE + ventUser.getPhone());
				ventUser.setPhone(userNewPhone).setUserName(userNewPhone);
				SecurityUtils.getSubject().getSession().setAttribute(Constants.SESSION_USER, ventUser);
			}
			return modifyStatus;
		} catch (Exception e) {
			log.error(e.toString(),e);
		}
		return "1";
	}
	//获取登录用户手机
	/*@RequestMapping("/getLoginUserPhone")
	public Object getLoginUserPhone() {
		PageData userPhonePd = new PageData(3);
		AppUser appUser = this.getSessionAppUser();
		if (appUser == null) {
			userPhonePd.put("status",-1);
			return userPhonePd;
		}
		userPhonePd.put("myPhone", appUser.getPhone());
		userPhonePd.put("status", "0");
		return userPhonePd;
	}
*/
	//未登录的验证码方式修改密码(目前就前端登录页面，“忘记密码”修改密码)
	@RequestMapping("/modifyPwdByCodeWithNoLogin")
	public Object modifyPwdByCodeWithNoLogin() {
		PageData pd = this.getPageData();
		try {
			String myPhone = pd.getString("myPhone"), newPwd = (String) pd.remove("newPwd"), checkCode = (String) pd.remove("checkCode");
			return ventUserService.modifyPwdByCheckCode(myPhone,newPwd,checkCode);
		} catch (Exception e) {
			log.error(e.toString(),e);
			pd.put("status", "1");
		}
		return pd;
	}
    //通过旧密码修改新密码
    @RequestMapping("/modifyPwdByOld")
    public Object modifyPwdByOld() {
        PageData pd = this.getPageData();
        try {
            VentUser ventUser = getSessionUser();
            if (ventUser == null){
                pd.put("status", "-1");
                return pd;
            }
            String oldPwd = pd.getString("oldPwd"), newPwd = (String) pd.remove("newPwd");
            return ventUserService.modifyPwdByOld(ventUser.getPhone(),newPwd,oldPwd);
        } catch (Exception e) {
            log.error("通过旧密码修改新密码错误：",e);
            pd.put("status", "1");
        }
        return pd;
    }
	//获取“我的主页”中的用户信息
	@RequestMapping(value="/getMyInfo")
	public Object getMyInfo(){
		PageData myInfoPd = new PageData(3);
		VentUser ventUser = getSessionUser();
		myInfoPd.put("status", -1);
		if (ventUser == null){
			return myInfoPd;
		}
		myInfoPd.put("ventUserId",ventUser.getUserId());
		ventUser = ventUserService.getHisInfo(myInfoPd,false);
		myInfoPd.clear();
		myInfoPd.put("status", 0);
		myInfoPd.put("my", ventUser);
		return myInfoPd;
	}
    //获取“我的主页”中的主页访问次数数据
    @RequestMapping(value="/countHomeAccessNum")
    public Object countHomeAccessNum(@RequestParam String year){
        PageData countPd = new PageData(3);
        if (countPd.getInt("status") == -1){
            return countPd;
        }
        initCountParam(countPd,year);
        List<PageData> homeAccessList = userCountService.countHomeAccessNum(countPd);
        return ControllerUtil.countResult(countPd,homeAccessList);
    }
    //获取“我的主页”中的主页访问次数数据
    @RequestMapping(value="/countAccessSiteNum")
    public Object countAccessSiteNum(@RequestParam String year){
        PageData countPd = new PageData(3);
        initCountParam(countPd,year);
		if (countPd.getInt("status") == -1){
			return countPd;
		}
        List<PageData> accessSiteList = userCountService.countAccessSiteNum(countPd);
        return ControllerUtil.countResult(countPd,accessSiteList);
    }
    /**
     * 初始化参数
     * @param countPd 统计的参数
     * @param year 年
     */
    private void initCountParam(PageData countPd,String year){
        VentUser ventUser = getSessionUser();
        if (ventUser == null){
            countPd.put("status", -1);
            return;
        }
        if (StringUtils.isEmpty(year)){
            String nowDate = DateUtil.getNowDate("-");
            year = nowDate.substring(2,4);
        }
        countPd.put("year",year);
        countPd.put("ventUserId",ventUser.getUserId());
    }
	//获取“我的主页”中的用户信息
	@RequestMapping(value="/updateHeaderImg")
	public Object updateHeaderImg(){
		PageData headerImgPd = new PageData(3);
		VentUser ventUser = getSessionUser();
		headerImgPd.put("status", -1);
		if (ventUser == null){
			return headerImgPd;
		}
		String userId = ventUser.getUserId();
		String headerImgPath = ventUserService.getHeaderImgPath(userId);
		headerImgPd.put("headerImgPath",getRequest().getParameter("headerImgPath"));
		headerImgPd.put("userId", userId);
		ventUserService.editHeaderImg(headerImgPd);
		headerImgPd.clear();
		headerImgPd.put("status", 0);
		String imgDelPathAndName = uploadPath + File.separator + headerImgPath;
		FileUtil.deleteFile(imgDelPathAndName);
		return headerImgPd;
	}
}